package com.du.web.sample.util;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @desc:
 * @author: shuangdu
 * @date: 2021/9/18
 * @since: 1.8
 */
@Slf4j
public class ConvertUtil {

    /**
     * doc文档转换为html
     * <p>
     *     注意：
     *     1. 需要有一个存放word图片的文件夹
     *     2. 转化后的样式存在差别
     *     3. 一些字体会无法显示
     * </p>
     * @param doc
     * @param docPath
     * @return
     */
    public static String toHtml(HWPFDocument doc, String docPath) {
        String content = null;
        try {
            final Path imagePath = Paths.get(docPath).resolve("image");
            File imgDoc = imagePath.toFile();
            if (!imgDoc.exists()) {
                boolean _add = imgDoc.mkdirs();
                if (_add) log.info("添加图片文件夹: {}", imgDoc.getAbsolutePath());
            }
            WordToHtmlConverter htmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            // 保存图片，并返回图片的相对路径
            htmlConverter.setPicturesManager(new PicturesManager() {
                @Override
                public String savePicture(byte[] content, PictureType pictureType, String name, float width, float height) {
                    try (FileOutputStream out = new FileOutputStream(imagePath.resolve(name).toString())) {
                        out.write(content);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return docPath + File.separator + "image" + File.separator + name;
                }
            });

            htmlConverter.processDocument(doc);
            Document document = htmlConverter.getDocument();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            DOMSource domSource = new DOMSource(document);
            StreamResult streamResult = new StreamResult(out);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "html");
            transformer.transform(domSource, streamResult);

            out.close();

            content = out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return content;
    }

    /**
     * html内容转为pdf
     * <p>
     *     利用的itext转pdf组件，转化后的pdf样式存在差异
     * </p>
     * @param htmlStr
     * @param pdfPath
     */
    public static void toPdf(String htmlStr, String pdfPath) {
        ConverterProperties converterProperties;
        try {

            FontProvider fontProvider = new FontProvider();
            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");

            converterProperties = new ConverterProperties();
            converterProperties.setFontProvider(fontProvider);

            OutputStream outputStream = new FileOutputStream(new File(pdfPath));
            HtmlConverter.convertToPdf(htmlStr, outputStream, converterProperties);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
